/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package za.co.sbi.sbiexam.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author sparkyspider
 */
public class ServiceController {
	
	private HttpServletRequest request = null;
	private HttpServletResponse response = null;
	private PrintWriter out = null;
	private String path = "";
	private Session session = null;


	public ServiceController (HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ClassNotFoundException {
		this.request = request;
		this.response = response;
		this.out = response.getWriter();
		this.path = getPathInfo();
		this.session = createSession();
	}

	public PrintWriter getOut() {
		return out;
	}

	public String getPath() {
		return path;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public Session getSession() {
		return session;
	}

	// Functions

	private String getPathInfo() {
		String p = request.getPathInfo();
		if (p.endsWith("/")) {
			p = p.substring(0, p.length() - 1);
		}
		return p;
	}

	private Session createSession() throws SQLException, ClassNotFoundException {

		Session session = Session.createSessionFromCookie(request);
		if (session == null) {
			session = Session.createNewSession();
		}
		return session;

	}

	void handleError(Exception ex) {

		String stackTrace = getStackTrace(ex);
		String firstLine = stackTrace.substring(0, stackTrace.indexOf("\n"));

		response.setContentType("text/plain");
		response.setStatus(HttpServletResponse.SC_OK);

		StringBuilder sb = new StringBuilder();

		sb.append("{\n");
		sb.append("\t\"response\":\"error\",\n");
		sb.append("\t\"errortype\":\"Internal Server Error: ").append(firstLine).append("\",\n");
		sb.append("\t\"errormessage\":\"").append(stackTrace.replace("\n", "<br/>")).append("\"\n");
		sb.append("}\n");

		out.print(sb.toString());
		out.close();
	}

	public void sendResponse(Session session) {
		response.setStatus(HttpServletResponse.SC_OK);
		response.addCookie(session.getResponseCookie());

		System.out.println("Printing...");

		Set<Map.Entry> entries = session.getResponseFields().entrySet();

		System.out.println("There are " + entries.size() + " entries...");

		StringBuilder sb = new StringBuilder();
		sb.append("{\n");

		for (Map.Entry<String, String> entry : entries) {
			sb.append("\t\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\",\n");
		}
		
		int lastCommaPosition = sb.lastIndexOf(",");
		String result = sb.substring(0, lastCommaPosition) + "\n" + "}";

		out.print(result);
		
		out.flush();
		out.close();


	}

	private String getStackTrace(Exception ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        String stackTrace = sw.toString();

        return stackTrace;
    }

}
